<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="站点类型" prop="terminalType">
        <el-select
          v-model="queryParams.terminalType"
          placeholder="请选择站点类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.TERMINAL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="站点标识" prop="appId">
        <el-input
          v-model="queryParams.appId"
          placeholder="请输入站点标识"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="站点名称" prop="appName">
        <el-input
          v-model="queryParams.appName"
          placeholder="请输入站点名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="绑定域名" prop="bindDomain">
        <el-input
          v-model="queryParams.bindDomain"
          placeholder="请输入绑定域名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="approveStatus">
        <el-select
          v-model="queryParams.approveStatus"
          placeholder="请选择审核状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['cms:app-site:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['cms:app-site:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @cell-click="listTableCellClickHandler"
    >
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="站点类型" align="center" prop="terminalType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TERMINAL" :value="scope.row.terminalType" />
        </template>
      </el-table-column>
      <el-table-column label="站点标识" align="center" prop="appId" />
      <el-table-column label="站点名称" align="center" prop="appName" />
      <el-table-column label="站长类型" align="center" prop="userType">
        <template #default="scope">
          <dict-tag
            v-if="scope.row.userType"
            :type="DICT_TYPE.USER_TYPE"
            :value="scope.row.userType"
          />
        </template>
      </el-table-column>
      <el-table-column label="站长编号" align="center" prop="userId" />
      <el-table-column label="站长" align="center" prop="userNickname" />
      <el-table-column label="LOGO" align="center" prop="appLogoUrl">
        <template #default="scope">
          <el-image
            class="h-60px max-w-60px"
            v-if="scope.row.appLogoUrl"
            :key="scope.row.appLogoUrl"
            :src="scope.row.appLogoUrl"
            :preview-src-list="[scope.row.appLogoUrl]"
            :initial-index="0"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column label="绑定域名" align="center" prop="bindDomain">
        <template #default="scope">
          <el-link :href="scope.row.bindDomain" target="_blank">{{ scope.row.bindDomain }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="站点简介" align="center" prop="appShortDesc" />
      <el-table-column label="状态[点击修改]" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="审核[点击修改]" align="center" prop="approveStatus">
        <template #default="scope">
          <dict-tag
            :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS"
            :value="scope.row.approveStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openConfigForm('update', scope.row.id)"
            v-hasPermi="['cms:app-site:update']"
          >
            站点配置
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['cms:app-site:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['cms:app-site:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AppSiteForm ref="formRef" @success="getList" />
  <AppSiteConfigForm ref="formConfigRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AppSiteApi, AppSiteVO } from '@/api/cms/appsite'
import AppSiteForm from './AppSiteForm.vue'
import AppSiteConfigForm from './AppSiteConfigForm.vue'
import { ref } from 'vue'
import { ElMessageBox, ElSwitch } from 'element-plus'

/** 站点 列表 */
defineOptions({ name: 'AppSite' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<AppSiteVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  terminalType: undefined,
  appId: undefined,
  appName: undefined,
  createTime: [],
  status: undefined,
  approveStatus: undefined,
  bindDomain: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 站点配置操作 */
const formConfigRef = ref()
const openConfigForm = (type: string, id?: number) => {
  formConfigRef.value.open(type, id)
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AppSiteApi.getAppSitePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const listTableCellClickHandler = async (row: AppSiteVO, column: any) => {
  if (column.property === 'status') {
    try {
      // 删除的二次确认
      await message.confirm(
        `确定${row.status === 0 ? '关闭' : '开启'}编号为【${row.id}】的站点吗？`
      )
      // 发起删除
      await AppSiteApi.updateAppSiteStatus({
        id: row.id,
        status: row.status === 0 ? 1 : 0
      } as AppSiteVO)
      message.success(t('common.updateSuccess'))
      // 刷新列表
      await getList()
    } catch {}
  }
  if (column.property === 'approveStatus' && row.approveStatus === 1) {
    try {
      const approveStatus = ref<number>(2)
      await ElMessageBox({
        title: '修改评论审核状态',
        // Should pass a function if VNode contains dynamic props
        message: () =>
          h(ElSwitch, {
            modelValue: approveStatus.value,
            activeText: '通过',
            inactiveText: '不通过',
            activeValue: 2,
            inactiveValue: 3,
            'onUpdate:modelValue': (val: boolean | string | number) => {
              approveStatus.value = val as number
            }
          })
      })
      await AppSiteApi.updateAppSiteApproveStatus({
        id: row.id,
        approveStatus: approveStatus.value
      } as AppSiteVO)
      message.success(t('common.updateSuccess'))
      // 刷新列表
      await getList()
    } catch {}
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AppSiteApi.deleteAppSite(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AppSiteApi.exportAppSite(queryParams)
    download.excel(data, '站点.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
